package com.jt.permission.service;

import com.jt.base.BaseService;
import com.jt.base.utils.Constant;
import com.jt.permission.mapper.UserMapper;
import com.jt.permission.mapper.UserRoleMapper;
import com.jt.permission.model.User;
import com.jt.permission.model.UserRole;
import com.jt.shiro.ShiroUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author longheping
 * @date 2018/6/21 15:47
 */
@Service
public class UserService extends BaseService<Long, User> {

  @Resource private UserRoleMapper sysUserRoleMapper;

   public List<String> queryAllPerms(Long userId){
       return ((UserMapper)mapper).queryAllPerms(userId);
    }

  /**
   * 更改密码
   */
    public User updatePassword(User sysUser,String password){
      sysUser.setPassword(ShiroUtils.sha256(password, sysUser.getSalt()));
      update(sysUser);
      return sysUser;
    }


  /**
   * 保存用户以及用户角色信息
   * @param sysUser
   * @param roleIdList
   * @return
   */

    public User saveOrUpdateUserRole(User sysUser,List<Long> roleIdList){

      boolean isNew = true;
      if(sysUser.getUserId()!=null){
        User sysUserDb =  selectByKey(sysUser.getUserId());
        if(sysUserDb!=null){//已经存在数据库的对象
          isNew = false;
          if(sysUser.getUserId()!= Constant.SUPER_ADMIN){//超级管理员不删除角色
            Example example = new Example(UserRole.class);
            example.createCriteria().andEqualTo("userId",sysUser.getUserId());
            sysUserRoleMapper.deleteByExample(example);//删除已经存在的用户角色关系
          }
          sysUserDb.setEmail(sysUser.getEmail());
          sysUserDb.setMobile(sysUser.getMobile());
          sysUserDb.setStatus(sysUser.getStatus());
          this.update(sysUserDb);
        }
      }
      if(isNew){//如果是新插入的对象
        String salt = RandomStringUtils.randomAlphanumeric(20);
        sysUser.setCreateTime(new Date());
        sysUser.setSalt(salt);
        sysUser.setPassword(ShiroUtils.sha256(Constant.SYS_USER_INIT_PASSWORD,salt));
        insert(sysUser);
      }
      if(sysUser.getUserId()!=Constant.SUPER_ADMIN){//超级管理员不更改角色
        for (Long id : roleIdList) {//保存新的用户角色关系
          UserRole userRole = new UserRole();
          userRole.setRoleId(id);
          userRole.setUserId(sysUser.getUserId());
          sysUserRoleMapper.insertUseGeneratedKeys(userRole);
        }
      }
      return sysUser;
    }
}
